<?php
namespace Web\Controller;
use Think\Controller;
use Web\Logic\MenuLogic;
use Web\Logic\IndexLogic;
use Web\Logic\CommonLogic;
class IndexController extends BaseController {
    public function index(){
        $this->display();
    }
    public function  login(){
        if(IS_POST){
            //实例化Logic
            $logic = new IndexLogic();
            //接受参数
            $data = $_REQUEST['data'];
            //验证用户名和密码不能为空
            if($data['username'] && $data['password']){
                //md5加密
                $data['password'] = md5($data['password']);
                //查询用户信息
                $udata = $logic->selUserInfo($data);
                //数据判断
                if($udata){
                    if($data['remember'] == 1){
                        cookie('flag', 1);
                        cookie('username', $data['username']);
                    } else {
                        cookie('flag', null);
                        cookie('username', null);
                    }
                    //判断用户是否可用
                    if($udata['isforbidden'] === '0' &&  $udata['eisforbidden'] === '0'){
                        //保存数据
                        //后台Session
                        session(C('SESSION_ADMIN_ID'), $udata['userid']);
                        session(C('SESSION_ADMIN_NAME'), $udata['username']);
                        session('headpic', $udata['image_url']);
                        //权限
                        if(!$udata['menuroot']){
                           $udata['menuroot'] ="-1";
                        }
                        session('menuroot', $udata['menuroot']);
                        session('rolename', $udata['rolename']);
                        session('roleid', $udata['roleid']);
                        session('function_id', $udata['function_id']);
                        //writeLog($userid, $act_type, $act_content='', $value, $device_id, $cpn_name='')
                        M('member')->where(array('userid'=>session(C('SESSION_ADMIN_ID'))))->setField('is_online', 1);
                        writeLog($udata['userid'], 1, '用户登录', '');
                        exit('<script>parent.location="'.U(C('PRO_INDEX')).'";</script>');

                    }else{
                        exit('<script>parent.notify("error", "提示", "用户不可用，请联系管理！");</script>');
                    }
                }else{
                    exit('<script>parent.notify("error", "提示", "用户名或密码不正确！");</script>');
                }
            }else{
                exit('<script>parent.notify("error", "提示", "用户名或密码为空！");</script>');
            }
        } else {
            //调用模板
            $this->display();
        }
    }


    /**
     * 退出登录
     * @access public
     * @author:wuhaiying <2014-02-10>
     * @update:<2014-02-10>
     * @note:
     */
    public function logout() {
        M('member')->where(array('userid'=>session(C('SESSION_ADMIN_ID'))))->setField('is_online', 0);
        writeLog(session(C('SESSION_ADMIN_ID')), 1, '用户退出', '');
        session(C('COOKIE_USER_ID'),null);
        session(C('COOKIE_USER_NAME'),null);
        session(C('SESSION_ADMIN_ID'),null);
        session(C('SESSION_ADMIN_NAME'),null);
        session(null);
        $this->success("退出成功",'login'); //重定向登录页面
    }

    public function register(){
        if(IS_POST){
            $rules = array(
                array('username','require','用户名称必填！'), //默认情况下用正则进行验证
                array('username','','用户名称已经存在！',0,'unique'),
                array('company','require','公司名称必填！'),
                array('email','require','Email必填！'),
                array('email','','Email已经存在！',0,'unique'),
                array('repassword','password','确认密码不正确',0,'confirm'), // 验证确认密码是否和密码一致
            );

            $Member = M('member');
            if (!$Member->validate($rules)->create()){
                exit('<script>parent.notify("error", "提示", "' . $Member->getError() . '");</script>');
            }else{
                $Member->password = md5(I('password'));
                $Member->roleid = 26;
                $Member->project_num = 2;
                $Member->created_at = date('Y-m-d H:i:s');
                $Member->updated_at = date('Y-m-d H:i:s');
                $Member->is_online = 1;
                $ins = $Member->add();
            }

            if($ins !== false){
                $data['user_id'] = $ins;
                $data['company'] = I('company');
                M('member_info')->add($data);
                //公司名称中增加公司名记录
                $add_company['company_name'] = $data['company'];
                $count = M('member_company')->where($add_company)->count();
                
                
                if($count == 0){
                    $add_company['is_show'] = 1;
                    M('member_company')->add($add_company);
                    
                }

                //session(C('SESSION_ADMIN_ID'), $ins);
                //session(C('SESSION_ADMIN_NAME'), I('username'));
                echo '<script>parent.notify("success", "提示", "保存成功！");parent.location="' . U('login') . '";</script>';
            } else {
                echo '<script>parent.notify("error", "提示", "保存失败！");</script>';
            }
        } else {
            $companys = M('member_company')->distinct(true)->order('company_name')->getField('company_name', true);

            $this->assign('companys', $companys);
            $this->display();
        }
    }

    /**
     * 验证码
     */
    public function verify_c(){
        ob_clean();
        $Verify = new \Think\Verify();
        $Verify->fontSize = 25;
        $Verify->length   = 4;
        $Verify->useNoise = false;
        $Verify->codeSet = '0123456789';
        $Verify->imageW = 170;
        $Verify->imageH = 50;
        $Verify->expire = 600;
        $Verify->entry();
    }

    // 检测输入的验证码是否正确，$code为用户输入的验证码字符串
    function check_verify($code, $id = ''){
        $verify = new \Think\Verify();
        return $verify->check($code, $id);
    }

    //忘记密码
	public function forget(){
		$email = I('email');
		if(IS_POST){
			if($email){
				$vo = M('member')->where(array('email'=>$email))->find();
				if($vo){
					$username = $vo['username'];
					$k = strtr(base64_encode(encrypt('q1w2e3r4', $vo['userid'].'|'.time())),'+/','-*');
					$url = 'http://'.$_SERVER['HTTP_HOST'].U('Index/resetPwd',array('k'=>$k));

					$content = <<<EOT
<p>尊敬的：{$username}</P>
<br/>
<p>你正在进行重置用户登录密码操作，请点击下面的链接，完成密码重置。</P>
<p><a href="{$url}">立即重置密码</a></P>
<p>如果点击无效，请复制下方网页地址到浏览器地址栏中打开：</P>
<p>{$url}</P>
<p>此为系统邮件，请勿回复。此邮件24小时有效！<em>邻元科技（北京）科技有限公司</em></P>
EOT;
					if(sendMail($email,'邻元科技（北京）科技有限公司软件设计平台 - 用户账号密码重置',$content)){
						$this->ajaxReturn(array('code'=>1, 'msg'=>'密码重置邮件发送成功！', 'data'=>''));
					} else {
						$this->ajaxReturn(array('code'=>0, 'msg'=>'邮件发送失败，请稍后再试！', 'data'=>''));
					}
				} else {
					$this->ajaxReturn(array('code'=>0, 'msg'=>'邮件地址不存在！', 'data'=>''));
				}
			} else {
				$this->ajaxReturn(array('code'=>0, 'msg'=>'邮件地址为空！', 'data'=>''));
			}
		} else {
			$this->display();
		}
	}

	//重设密码
	public function resetPwd(){
		$k = I('request.k');
		$k = decrypt('q1w2e3r4', base64_decode(strtr($k, '-*', '+/')));
		$arr = explode('|', $k);
		if(count($arr) > 1){
			if(time()-$arr[1] > 86400){
				exit('<script>alert("您的密码重置邮件有效期已过，请您重新发送密码重置邮件.");</script>');
			}
		} else {
			exit('<script>alert("地址参数错误.");</script>');
		}

		if(IS_POST){
			$rules = array(
                array('password','require','密码必填'),
				array('repassword','pwd','确认密码不正确',0,'confirm'),
			);

			$Member = M('member');

			if (!$Member->validate($rules)->create()){
				 $this->ajaxReturn(array('code'=>0, 'msg'=>$Member->getError(), 'data'=>''));
			}else{
				$Member->userid = $arr[0];
				$Member->password = md5($Member->password);
				$Member->save();
				$this->ajaxReturn(array('code'=>1, 'msg'=>'密码重置成功！', 'data'=>''));
			}
		} else {
			$username = M('member')->where(array('userid'=>$arr[0]))->getField('username');

			$this->assign('username', $username);
			$this->display();
		}
	}

}